<template>
	<div
		class="m-view-common-layout"
	>
		<!-- 左侧树区域 star-->
		<div
			v-if="columnData.type === 2"
			class="m-view-common-layout-left"
		>
			<div
				v-if="columnData.treeTitle"
				class="m-view-common-title"
			>
				<h2>{{columnData.treeTitle}}</h2>
				<Dropdown v-if="columnData.treeSynType === 0">
					<Link
						icon="icon-ym icon-ym-mpMenu"
						:underline="false"
					/>
					<template #dropdown>
						<DropdownItem>
							<DropdownItem @click="toggleTreeExpand(true)">
								展开全部
							</DropdownItem>
							<DropdownItem @click="toggleTreeExpand(false)">
								折叠全部
							</DropdownItem>
						</DropdownItem>
					</template>
				</Dropdown>
			</div>
			<div
				v-if="columnData.hasTreeQuery && columnData.treeSynType === 0"
				class="m-view-common-tree-search-box"
			>
				<Input
					v-model="keyword"
					placeholder="输入关键字"
					suffix-icon="el-icon-search"
					clearable
				/>
			</div>
			<!-- 左侧树 -->
			<Tree
				v-if="refreshTree"
				ref="treeBox"
				:data="treeData"
				:props="treeProps"
				:default-expand-all="columnData.treeSynType === 0 ? expandsTree : false"
				highlight-current
				:expand-on-click-node="false"
				class="m-view-common-el-tree"
				:node-key="treeProps.value"
				:filter-node-method="filterNode"
				:lazy="!!((columnData.treeSynType === 1) & (columnData.treeDataSource === 'api'))
				"
				:load="loadNode"
				@node-click="handleNodeClick"
			>
				<template #default="{ node, data }">
					<span class="m-view-custom-tree-node">
						<i :class="data.icon"/>
						<span class="text">{{node.label}}</span>
					</span>
				</template>
			</Tree>
		</div>
		<!-- 左侧树区域 end-->

		<div class="m-view-common-layout-center">
			<!--搜索栏 star -->
			<Search
				ref="Search"
				:list="columnData.searchList"
				:init-data-json="listQuery.query"
				@reset="reset"
				@search="search"
			/>
			<!--搜索栏 end -->

			<div class="m-view-common-layout-main m-view-flex-main">
				<!-- 功能栏 star -->
				<div class="m-view-common-head">
					<div>
						<Checkbox
							v-if="viewType==='card'&&columnData.enableSelect"
							v-model="selectAllValue"
							class="m-view-common-head__checkbox"
							:indeterminate="indeterminate"
							@change="handleSelectAll"
						>
							全选
						</Checkbox>
						<!-- 功能栏左前插槽-->
						<slot
							name="top-left-before"
							style="margin-right: 10px;"
						/>
						<Button
							v-for="(item, i) in columnData.btnsList"
							:key="i"
							:icon="item.icon"
							type="primary"
							:style="{ backgroundColor: item.color, borderColor: item.color}"
							@click="headBtnsHandel(item)"
						>
							{{getTrans('btns', modelId, item.value)}}
						</Button>
						<!-- 功能栏左后插槽-->
						<slot name="top-left-after"/>
					</div>

					<div class="m-view-common-head-right">
						<!-- 功能栏右前插槽-->
						<slot name="top-right-before"/>

						<Button
							v-for="item in columnData.navigateBtnsList"
							:key="item.value"
							type="primary"
							:icon="item.icon"
							plain
							@click="handleJump(item)"
						>
							{{getTrans('btns',modelId,item.value)}}
						</Button>
						<SwitchButton
							v-if="columnData.type === 6"
							ref="SwitchButtonRef"
							:items="ViewToggleItems"
							:theme-color="themeColor"
							@change="changeViewModel"
						/>
						<!-- 功能栏右后插槽-->
						<slot name="top-right-after"/>

						<Tooltip
							effect="dark"
							:content="t('刷新')"
							placement="top"
						>
							<Link
								icon="el-icon-refresh global-common-head-icon"
								:underline="false"
								@click="initData()"
							/>
						</Tooltip>

						<Tooltip
							v-if="columnData.hasSuperQuery"
							:content="t('高级查询')"
							placement="top"
						>
							<Link
								icon="el-icon-zoom-in m-view-common-head-icon"
								:underline="false"
								@click="openSuperQuery()"
							/>
						</Tooltip>

						<template v-if="columnData.treeLazyType === 0">
							<Tooltip
								effect="dark"
								:content="expandsTable ? '折叠' : '展开'"
								placement="top"
							>
								<Link
									type="text"
									:icon="expandsTable ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
									:underline="false"
									class="m-view-common-head-icon"
									@click="toggleExpandList()"
								/>
							</Tooltip>
						</template>
					</div>
				</div>
				<!-- 功能栏 end -->

				<!-- 表格 star-->
				<Table
					v-if="viewType==='list'"
					ref="tableRef"
					v-loading="loading"
					element-loading-text="loading..."
					:data="list"
					row-key="id"
					:row-style="rowStyle"
					:cell-style="cellStyle"
					:header-cell-style="headerCellStyle"
					@selection-change="handleSelectionChange"
					@row-dblclick="rowDblclick"
					@cell-click="cellClick"
				>
					<!--选择框-必须使用div包裹-->
					<div v-if="columnData.enableSelect">
						<TableColumn
							type="selection"
							width="50"
							align="center"
							:reserve-selection="true"
						/>
					</div>
					<!--序号-->
					<TableColumn
						type="index"
						width="50"
						:label="t('序号')"
						align="center"
					/>
					<!-- 普通表格 -->
					<template v-for="(item, i) in columnList">
						<!-- 设计子表 -->
						<template v-if="item.identity === 'table'">
							<TableColumn
								v-if="columnData.childTableStyle !== 2"
								:key="i"
								:prop="item.prop"
								:label="getTrans('fields',modelId,item.prop)"
								:align="item.align"
							>
								<TableColumn
									v-for="(child, ii) in item.children"
									:key="ii"
									:prop="child.prop"
									:label="getTrans('fields',modelId,child.prop)"
									:align="child.align"
									:width="child.width"
									:sortable="child.sortable ? 'custom' : child.sortable"
									class-name="child-table-box"
								>
									<template #default="scope">
										<ChildTableColumn
											v-if="!ii"
											:data="scope.row[item.prop]"
											:head="item.children"
											:expand="scope.row[`${item.prop}Expand`]"
											@toggle-expand="
												toggleExpand(scope.row, `${item.prop}Expand`)
											"
											@to-detail="toDetail"
										/>
									</template>
								</TableColumn>
							</TableColumn>
						</template>
						<!-- 其他 -->
						<template v-else>
							<TableColumn
								v-if="!item.hidden"
								:key="i"
								:label="getTrans('fields',modelId,item.prop)"
								:align="item.align"
								:fixed="getFixed(item, i)"
								:width="item.width"
								:sortable="item.sortable ? 'custom' : item.sortable"
								:prop="item.prop"
							>
								<template #default="scope">
									<!--关联表单-->
									<div v-if="item.identity === 'relationForm'">
										<Link
											:underline="false"
											type="primary"
											@click="toDetail(item, scope.row[`${item.prop}_id`])"
										>
											{{scope.row[item.prop]}}
										</Link>
									</div>

									<!-- 标签渲染 -->
									<template v-else-if="columnListKeys.includes(item.prop + '.tag')">
										<TagRenderer
											:data="scope.row"
											:field="item.prop"
										/>
									</template>

									<!-- 默认文本渲染 -->
									<template v-else>
										<i
											v-if="item.columnStyle && item.columnStyle.leftIcon"
											:class="item.columnStyle.leftIcon"
											@click="cellIconClick(item,'before')"
										/>
										<span class="column-scope">{{scope.row[item.prop]}}</span>
										<i
											v-if="item.columnStyle && item.columnStyle.rightIcon"
											:class="item.columnStyle.rightIcon"
											@click="cellIconClick(item,'after')"
										/>
									</template>
								</template>
							</TableColumn>
						</template>
					</template>
					<!-- 数据按钮 -->
					<TableColumn
						v-if="columnBtnsList.length"
						:label="t('操作')"
						fixed="right"
						:width="operationWidth"
					>
						<template #default="scope">
							<!-- 内置按钮 -->
							<template v-for="(item, i) in columnBtnsList">
								<Button
									v-if="['edit', 'remove', 'detail'].includes(item.value)"
									:key="`${item.value}-${i}`"
									size="mini"
									type="text"
									:class="item.value === 'remove' ? 'm-view-table-delBtn' : ''"
									@click="columnBtnsHandel(item.value, scope.row, scope.$index)"
								>
									{{getTrans('btns', modelId, item.value)}}
								</Button>
							</template>
							<!-- 扩展按钮 -->
							<template v-if="extendColumnBtns.length">
								<Dropdown hide-on-click>
									<span class="el-dropdown-link">
										<Button
											type="text"
											size="mini"
										>{{t('更多')}}<i
											class="el-icon-arrow-down el-icon--right"
										/></Button>
									</span>
									<template #dropdown>
										<DropdownItem>
											<DropdownItem
												v-for="(item, i) in extendColumnBtns"
												:key="i"
												@click="handleDataBtn(item, scope.row)"
											>
												{{getTrans('btns',modelId,item.value)}}
											</DropdownItem>
										</DropdownItem>
									</template>
								</Dropdown>
							</template>
						</template>
					</TableColumn>
				</Table>
				<!-- 表格 end-->

				<!-- 多条模板组件渲染容器 star-->
				<template v-else-if="componentMap&&componentMap[cardTemplateIdentity]&&viewType==='card'">
					<div
						v-loading="loading"
						class="extend-card"
					>
						<template v-if="list.length">
							<component
								:is="componentMap[cardTemplateIdentity]"
								v-for="item in list"
								:key="item.id"
								class="extend-item"
								:context="context"
								:data="item"
								@change="(val) => widgetInput(val, item)"
								@refresh="initData"
								@row-dblclick="rowDblclick"
							/>
						</template>
						<Empty
							v-else
							:description="t('数据为空')"
							class="data-empty"
						/>
					</div>
				</template>
				<!-- 多条模板组件渲染容器 end-->

				<!-- 单条模板组件渲染容器 star-->
				<template v-else-if="componentMap&&componentMap[singleCardTemplateIdentity]&&viewType==='page'">
					<template v-if="storedList.length">
						<component
							:is="componentMap[singleCardTemplateIdentity]"
							:data="storedList"
							:current-index="currentIndex"
							:context="context"
							@jump="pageJump"
						/>
					</template>
					<Empty
						v-else
						:description="t('数据为空')"
						class="data-empty"
					/>
				</template>
				<!-- 单条模板组件渲染容器 star-->

				<!--未对应注册组件时展示-->
				<div
					v-else
					class="data-empty"
				>
					<Empty :description="t('未检测到组件')"/>
				</div>

				<!-- 扩展卡片组件渲染容器 end-->

				<!-- 页脚 star-->
				<div
					v-if="shouldShowPagination"
					class="table-footer"
				>
					<span class="bottom-left-before">
						<slot name="bottom-left-before"/>
					</span>
					<Pagination
						:current-page="listQuery.currentPage"
						:page-size="listQuery.pageSize"
						background
						layout="total, sizes, prev, pager, next, jumper"
						:page-sizes="pageSizes"
						:total="total"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>
				<!-- 页脚 end-->
			</div>
		</div>
		<PopupForm
			v-show="formVisible"
			ref="Form"
			@refresh-data-list="refresh"
		/>
		<Detail
			v-if="detailVisible"
			ref="Detail"
			:list="list"
			@close="detailVisible = false"
			@change="changeItem"
		/>
		<RelevanceDetail
			v-if="detailsVisible"
			ref="RelevanceDetail"
			@close="detailsVisible = false"
		/>
		<ExportBox
			v-if="downloadVisible"
			ref="ExportBox"
			@download="download"
		/>
		<ImportBox
			v-if="uploadVisible"
			ref="UploadBox"
			@refresh="initData"
		/>
		<SuperQuery
			v-if="superQueryVisible"
			ref="SuperQuery"
			:column-options="columnOptions"
			@super-query="triggerSuperQuery"
		/>
		<!-- 扩展弹窗 -->
		<template v-if="widgetName&&componentMap&&componentMap[widgetName]">
			<component
				:is="componentMap[widgetName]"
				:ref="widgetName"
				:row="row"
				:data="row"
				:selection="selection"
				:context="context"
				@refresh="initData"
				@row-dblclick="rowDblclick"
			/>
		</template>
	</div>
</template>

<script>
// 样式和库引入
import Vue from 'vue';
import { magic, magicUtil } from '@lexmis/magic-ui/pc';
import { t, thousandsFormat, getScriptFunc } from '../../utils/index.js';
import generateLighterColor from '../../utils/calc-color.js';
import changeTheme from '../../utils/changeTheme';

// 组件引入
import {Dropdown,Link,DropdownItem,Input,Tree,Checkbox,Button,Tooltip,Table,TableColumn,Empty,Pagination} from 'element-ui';
import PopupForm from './Form';
import Detail from './detail';
import RelevanceDetail from './RelevanceDetail';
import Search from './Search';
import ChildTableColumn from './ChildTableColumn';
import SuperQuery from './SuperQuery';
import ImportBox from './ImportBox.vue';
import ExportBox from './ExportBox.vue';
import SwitchButton from './SwitchButton.vue';
import Icon from './Icon.vue';
import TagRenderer from './TagRenderer.vue';

// 配置引入
import { systemComponentsList } from '../../utils/config.js';
// 静态内置按钮
const staticBtns = ['add', 'edit', 'detail', 'remove', 'download', 'upload'];
export default {
	name:'DynamicModel',
	components:{
		PopupForm,
		Search,
		Detail,
		ChildTableColumn,
		RelevanceDetail,
		SuperQuery,
		ImportBox,
		ExportBox,
		SwitchButton,
		Icon,
		TagRenderer,
		Dropdown,
		Link,
		DropdownItem,
		Input,
		Tree,
		Checkbox,
		Button,
		Tooltip,
		Table,
		TableColumn,
		Empty,
		Pagination,
	},
	provide(){
		return {
			getTotal:this.getTotal,
			getQuery:this.getQuery,
			getSelection:this.getSelection,
			getData:this.getData,
			search:this.search,
			refresh:this.refresh,
			clearSelection:this.clearSelection,
			viewType:this.viewType,
			setActiveViewType:this.setActiveViewType,
		};
	},
	props:{
        //模板id
		modelId:{
			type:String,
			default:'',
		},
        //默认查询参数
		initialQuery:{
			type:Array,
			default:() => [],
		},
        //业务需要传递的上下文
		context:{
			type:Object,
			default:() => ({
				hasCheckBox:false,
			}),
		},
        //是否预览模式
		isPreview:{
			type:Boolean,
			default:false,
		},
        //组件列表
		componentMap:{
			type:Object,
			default:() => ({}),
		},
		//模拟数据
		mock:{
			type:Object,
			default:() => ({
				enabled:false,
				config:{},
				data:{},
				edit:{},
				detail:{}
			}),
		}
	},
	data(){
		return {
			t, // 国际化相关翻译函数
			pageSizes:[2, 20, 50, 100, 500], //每页条数
			viewType:'list', //当前视图类型
			currentIndex:0, //单条数据模式下当前索引
			themeColor:'', //主题色
			ViewToggleItems:[{label:'列表', value:'list'}, {label:'卡片', value:'card'}], //视图切换
			config:{}, // 配置对象
			cardTemplateIdentity:'', // 卡片模板标识
			singleCardTemplateIdentity:'', // 单条模板标识
			widgetName:'', // 当前小部件名称
			row:{}, // 当前行数据
			currentEditIndex:'', // 当前编辑行索引
			mainLoading:true, // 主加载状态
			systemComponentsList, // 系统组件列表
			keyword:'', // 搜索关键字
			treeProps:{ // 树结构属性配置
				children:'children', // 子节点字段
				label:'fullName', // 节点显示的名称字段
				value:'id', // 节点值字段
				isLeaf:'isLeaf', // 是否为叶子节点字段
			},
			list:[], // 数据列表
			columnListKeys:[], // 每一列的key
			storedList:[], //带缓存的list数据，翻页模式使用
			storedTotal:0, //翻页模式数据总条数
			cachePageListQuery:{ //翻页模式分页数据
				currentPage:1, // 当前页码
				pageSize:2, // 每页显示条数
				query:{
					matchLogic:'AND', // 查询逻辑
					condition:[], // 查询条件
				},
			},
			total:0, // 数据总条数
			loading:false, // 加载状态
			listQuery:{ // 列表查询参数
				currentPage:1, // 当前页码
				pageSize:2, // 每页显示条数
				query:{
					matchLogic:'AND', // 查询逻辑
					condition:[], // 查询条件
				},
			},
			cacheCondition:[], // 缓存的查询条件
			formVisible:false, // 表单弹窗显示状态
			detailVisible:false, // 详情弹窗显示状态
			detailsVisible:false, // 更多详情弹窗显示状态
			downloadVisible:false, // 下载弹窗显示状态
			uploadVisible:false, // 上传弹窗显示状态
			superQueryVisible:false, // 高级查询弹窗显示状态
			treeData:[], // 树结构数据
			expandsTree:true, // 树结构展开状态
			treeActiveId:'', // 当前树节点激活 ID
			columnData:{}, // 表格列数据
			formData:{}, // 表单数据
			columnList:[], // 表格列列表
			childColumnList:[], // 子表格列列表
			columnOptions:[], // 列配置选项
			exportList:[], // 导出的列列表
			columnBtnsList:[], // 列按钮列表
			refreshTable:false, // 刷新表格状态
			expandsTable:true, // 表格展开状态
			selectedIds:[], // 已选中的数据 ID 列表
			settingsColumnList:[], // 设置中的列列表
			mergeList:[], // 合并的列列表
			expandObj:{}, // 展开对象
			isCustomCopy:false, // 是否自定义复制
			candidateVisible:false, // 候选列表弹窗显示状态
			candidateType:1, // 候选列表类型
			branchList:[], // 分支列表
			candidateList:[], // 候选项列表
			currRow:{}, // 当前选中的行数据
			rowStyle:null, // 行样式
			refreshTree:true, // 刷新树结构状态
			key2:+new Date(), // 强制刷新使用的唯一键
			indeterminate:null, // 全选的半选状态
			selectAllValue:false, // 全选状态
			rowIndex:0, // 当前行索引
			conditionRef:[], // 查询条件引用
			cursomColumn:[], // 自定义列列表
			selection:[], // 表格选中项列表
		};
	},
	computed:{
        // 计算操作列的宽度
		operationWidth(){
			const customWidth = 0;
			return this.columnBtnsList.length * 50 + customWidth;
		},
        // 获取扩展的列按钮,过滤掉静态按钮
		extendColumnBtns(){
			return this.columnBtnsList.filter((item) => !staticBtns.includes(item.value));
		},
        // 判断是否显示分页
		shouldShowPagination(){
			return (
				this.columnData.type !== 3
				&& this.columnData.type !== 5
				&& this.columnData.hasPage
				&& this.refreshTable && this.viewType !== 'page'
			);
		},
	},
	watch:{
		keyword(val){
			if(this.columnData.treeSynType === 0)this.$refs.treeBox.filter(val);
		},
		themeColor:{
			immediate:true,
			handler(val){
				//使用主色生成一系列主题色
				if(val?.color?.primary?.main){
					changeTheme.changeThemeColor(val.color.primary.main);
				}
			},
		},
	},
	mounted(){
		// 获取 inject 传递的响应式主题数据
		this.themeColor = Vue.observable(magicUtil.injectTheme());
		this.getTemplateConfig();
	},
	methods:{
        //外部调用，获取查询条件
		getTotal(){
			return this.total;
		},
        //外部调用，获取查询条件
		getQuery(){
			return this.listQuery;
		},
        // 外部调用，获取已选中的数据
		getSelection(){
			return this.selection;
		},
        // 外部调用，获取列表数据
		getData(){
			return this.list;
		},
        // 获取模板配置
		getTemplateConfig(){
			//如果mock模式启用
			if(this.mock?.enabled){
				console.log(this.mock);
				this.config = this.mock.config;
				this.init();
				return;
			}
			if(!this.modelId){
				this.$message.error(t('无法加载表格数据，缺少模板id'));
				return;
			}
			magic.core
				.service({
					url:`/api/form/instance/config`,
					method:'get',
					params:{templateId:this.modelId},
				})
				.then(({data}) => {
					this.config = data;
					this.init();
				});
		},
		// 外部调用，更新翻页模式缓存数据
		changePageViewData(){
			return magic.core
				.service({
					url:'/api/form/instance/list',
					method:'post',
					data:{
						templateId:this.modelId,
						query:{
							matchLogic:'AND',
							condition:this.context.customQuery,
						},
						currentPage:this.cachePageListQuery.currentPage,
						pageSize:this.cachePageListQuery.pageSize,
					},
				})
				.then(({data}) => {
					this.storedTotal = data.total;

						// 使用 Promise.all 并处理每个项的详情请求
					return Promise.all(
						data.list.map((item) =>
							magic.core
								.service({
									url:'/api/form/instance/data-text',
									method:'get',
									params:{
										templateId:this.modelId,
										id:item.id,
									},
								})
								.then(({data}) => ({...item, ...data.data})),
						),
					);
				})
				.then((updatedList) => {
						// 将更新后的列表赋值给 storedList
					this.storedList = [...this.storedList, ...updatedList];
				})
				.catch(() => {
						// 错误处理
					this.loading = false;
					this.$emit('on-update');
				});
		},
		// 设置默认激活列表展示类型
		setActiveViewType(type){
			const item = this.ViewToggleItems.find((item) => item.value === type);
			if(item){
				// 获取当前项的索引
				const viewActiveIndex = this.ViewToggleItems.indexOf(item);
				this.$nextTick(() => {
					// 更新视图模型
					this.changeViewModel(type);
					const switchButtonRef = this.$refs.SwitchButtonRef;
					if(switchButtonRef){
						switchButtonRef.currentIndex = viewActiveIndex ?? 0;
						switchButtonRef.active = item.value;
					}
				});
			}
		},
        // 处理全选操作
		handleSelectAll(val){
			for(const item of this.list){
				item.checked = val;
			}
		},
        // 处理扩展组件的输入变化和选择变化
		widgetInput(val, item = null){
			if(item !== null){
				// 如果是输入变化，更新单个 item 的 checked 状态
				item.checked = val;
			}
			// 获取选中的 id 数组
			const checkedList = this.list.filter((item) => item.checked);
			const selectedIds = checkedList.map((v) => v.id);

			// 根据选中的 id 数组计算选择状态
			const allSelected = selectedIds.length === this.list.length;
			const noneSelected = selectedIds.length === 0;
			this.indeterminate = !noneSelected && !allSelected;
			this.selectAllValue = allSelected;
			this.selection = checkedList;
		},
        // 切换视图模式
		changeViewModel(viewType){
			this.viewType = viewType;
			//切换为表格模式后选中勾选
			this.$nextTick(() => {
				if(this.viewType === 'list'){
					this.$nextTick(() => {
						const tableRef = this.$refs.tableRef;
						for(const item of this.selection){
							const row = this.list.find((listItem) => listItem.id === item.id);
							if(row){
								tableRef.toggleRowSelection(row, true);
							}
						}
					});
				}
			});
		},
        // 导航跳转
		handleJump(item){
			this.$router.push('/' + item.value);
		},
        // 初始化加载
		async init(){
			this.loading = true;
			this.refreshTable = false;
			const {columnData, formData} = this.config;
			if(!columnData || !formData){
				this.$message.error(t('未配置表单数据或列数据'));
				return;
			}
			this.columnData = columnData;
			this.formData = formData;
			this.cardTemplateIdentity = columnData.cardTemplateIdentity;
			//设置单条模板
			if(columnData.singleCardTemplateIdentity){
				this.singleCardTemplateIdentity = columnData.singleCardTemplateIdentity;
				this.ViewToggleItems.push({label:'翻页', value:'page'});
			}
			this.columnBtnsList = columnData.columnBtnsList || [];
			this.columnOptions = columnData.columnOptions || [];

             // 设置行样式和单元格样式（如有定义）
			this.rowStyle = getScriptFunc.call(this, columnData?.funcs?.rowStyle?.func);

             // 获取列配置
			this.getColumnList();

             //筛选出设置了自定义列样式的列
			this.cursomColumn = this.columnList.filter((item) => item.columnStyle && item.columnStyle.color);

            // 延迟刷新表格
			this.$nextTick(() => (this.refreshTable = true));

            // 退出预览模式则停止加载状态
			if(this.isPreview) return (this.loading = false);

            // 设置默认查询参数
			this.listQuery.query.condition = this.initialQuery;
			const {hasPage, type} = columnData;

            // 非分页模式时，设置更大的 pageSize
			if(type === 3 || !hasPage){
				this.listQuery.pageSize = 10000;
			}

            // 配置树形结构属性（如果类型为 2）
			if(type === 2){
				this.treeProps = {
					value:columnData.treePropsValue || 'id',
					label:columnData.treePropsLabel || 'fullName',
					children:columnData.treePropsChildren || 'children',
				};
				this.getTreeView();
			}else{
				await this.initData();
				await this.getFirstLoadDataDetail();
				this.$emit('on-load');
			}
		},
		// 如果是第一次加载并且是单卡模板标识，获取详细信息
		getFirstLoadDataDetail(){
			if(this.singleCardTemplateIdentity && !this.mock?.enabled){
				this.list.map((item, index) => {
					return magic.core.service({
						url:'/api/form/instance/data-text',
						method:'get',
						params:{templateId:this.modelId, id:item.id},
					}).then(({data:detailData}) => {
						// 更新存储的项
						this.$set(this.storedList, index, {...item, ...detailData.data});
					});
				});
			}
		},
		// 获取列表数据
		initData(){
			//如果是mock模式
			if(this.mock?.enabled){
				this.list = this.mock.data.list;
				this.total = this.mock.data.total;
				return;
			}
			if(this.isPreview) return;

			this.loading = true;

			// 合并查询条件，去重操作
			this.listQuery.query.condition = [
				...this.listQuery.query.condition,
				...this.cacheCondition,
			].filter((item, index, self) => index === self.findIndex((t) => t.model === item.model));

			this.listQuery.query.matchLogic = 'AND';

			// 发起请求获取列表数据
			return magic.core
				.service({
					url:'/api/form/instance/list',
					method:'post',
					data:{
						templateId:this.modelId,
						query:this.listQuery.query,
						currentPage:this.listQuery.currentPage,
						pageSize:this.listQuery.pageSize,
					},
				})
				.then(({data}) => {
					const processItem = (item) => ({
						...item,
						...this.expandObj,
						hasChildren:true,
						checked:this.selection.some((selectedItem) => selectedItem.id === item.id),
					});

					const result = data.list.map(processItem);
					this.list = result;

					if(this.list.length){
						this.columnListKeys = Object.keys(this.list[0]);
					}

						// 更新总数
					this.total = data.total;
				})
				.finally(() => {
					this.loading = false;
					this.$nextTick(() => {
						if(this.columnData?.funcs?.afterOnload?.func){
							this.setTableLoadFunc();
						}
					});
					this.$emit('on-update');
				});
		},
		// 获取表格的汇总数据
		getTableSummaries(param){
			const thousandsField = [];
			this.columnList.forEach((res) => {
				if(res.thousands) thousandsField.push(res.model);
			});
			const {columns, data} = param;
			const sums = [];
			columns.forEach((column, index) => {
				if(index === 0){
					sums[index] = '合计';
					return;
				}else if(this.columnData.summaryField.includes(column.property)){
					const values = data.map((item) => Number(item[column.property]));
					if(!values.every((value) => isNaN(value))){
						sums[index] = values
							.reduce((prev, curr) => {
								const value = Number(curr);
								if(!isNaN(value)){
									return prev + curr;
								}else{
									return prev;
								}
							}, 0)
							.toFixed(2);
						if(thousandsField.includes(column.property)){
							sums[index] = thousandsFormat(sums[index]);
						}
					}else{
						sums[index] = '';
					}
				}
			});
			return sums;
		},
        // 查看详情
		toDetail(item, id){
			if(!id) return;
			this.mainLoading = true;
			magic.core
				.service({
					url:`/api/form/instance/config`,
					method:'get',
					params:{templateId:item.config.dataTypeId},
				})
				.then(({data}) => {
					this.mainLoading = false;
					const formData = data.formData;
					formData.popupType = 'general';
					this.detailsVisible = true;
					this.$nextTick(() => {
						this.$refs.RelevanceDetail.init(
							{...formData, popupWidth:item.popupWidth},
							item.config.dataTypeId,
							id,
						);
					});
				})
				.catch(() => {
					this.mainLoading = false;
				});
		},
        //根据类型获取树形数据
		getTreeView(){
			let url = '';
			let method = 'get';
			switch(this.columnData.treeDataSource){
				case 'dictionary':
					if(!this.columnData.treeDataSourceId) return;
					url = `/api/system/DictionaryData/${this.columnData.treeDataSourceId}/Data/Selector`;
					break;

				case 'form':
					url = `/api/form/instance/tree?templateId=${this.modelId}`;
					this.treeProps.label = 'name';
					break;

				case 'organize':
				case 'department':
					url = `/api/permission/Organize/Department/Selector`;
					break;

				case 'api':
					if(!this.columnData.treeDataSourceId) return;
					url = `/api/system/DataInterface/${this.columnData.treeDataSourceId}/Actions/Preview`;
					method = 'post';
					break;

				default:
					return;
			}
			magic.core
				.service({
					url,
					method,
				})
				.then(({data}) => {
					this.treeData = Array.isArray(data.list) ? data.list : Array.isArray(data) ? data : [];
					this.initData();
				})
				.catch((error) => {
					console.error('获取树形数据失败:', error);
				});
		},
        // 获取列列表
		getColumnList(){
			if(this.isPreview){
				const columnList = this.columnData.columnList;
				this.columnList = this.transformColumnList(columnList);
				return;
			}
			let columnPermissionList = [];
			if(!this.columnData.useColumnPermission){
				columnPermissionList = this.columnData.columnList;
			}else{
				const permissionList = this.$store.getters.permissionList;
				const modelId = this.$route.meta.modelId;
				const {column:columnList = []} = permissionList.find((o) => o.modelId === modelId) || {};
				columnPermissionList = this.columnData.columnList.filter((column) =>
					columnList.some((permission) => column.prop === permission.enCode),
				);
			}
			this.columnList = this.transformColumnList(columnPermissionList);
		},
        // 转换列数据，处理嵌套的列，并生成新的列结构
		transformColumnList(columnList){
			const list = [];
			const propMap = {};
			for(const e of columnList){
				if(!e.prop.includes('-')){
					list.push(e);
				}else{
					const [prop, model] = e.prop.split('-');
					const [label, ...childLabelParts] = e.label.split('-');
					const childLabel = childLabelParts.join('-');

					const newItem = propMap[prop] || {
						align:'center',
						identity:'table',
						prop,
						label,
						children:[],
					};
					e.model = model;
					e.childLabel = childLabel;
					if(!Object.prototype.hasOwnProperty.call(this.expandObj, `${prop}Expand`)){
						this.$set(this.expandObj, `${prop}Expand`, false);
					}
					if(!propMap[prop]){
						list.push(newItem);
						propMap[prop] = newItem;
					}
					newItem.children.push(e);
				}
			}
			this.getMergeList(list);
			this.getExportList(list);
			this.childColumnList = list.filter((o) => o.identity === 'table');
			return list;
		},
        // 生成导出列表
		getExportList(list){
			this.exportList = list.flatMap((item) =>
				item.identity === 'table' && this.columnData.type !== 4
					? item.children
					: [item],
			);
		},
        // 根据列的数据生成合并单元格的列表
		getMergeList(list){
			this.mergeList = list.reduce((acc, item) => {
				if(item.children?.length > 0){
					const children = item.children.map((child, index) => ({
						prop:child.prop,
						rowspan:index === 0 ? 1 : 0,
						colspan:index === 0 ? item.children.length : 0,
					}));
					acc.push(...children);
				}else{
					acc.push({
						prop:item.prop,
						rowspan:1,
						colspan:1,
					});
				}
				return acc;
			}, []);
		},
        // 用于表格中合并单元格时，返回具体的行列跨度
		arraySpanMethod({column}){
			for(let i = 0; i < this.mergeList.length; i++){
				if(column.property === this.mergeList[i].prop){
					return [this.mergeList[i].rowspan, this.mergeList[i].colspan];
				}
			}
		},
        // 切换某一行的展开状态
		toggleExpand(row, field){
			row[field] = !row[field];
		},
        // 获取树节点的完整路径
		getNodePath(node){
			const fullPath = [];
			const loop = (node) => {
				if(node.level) fullPath.unshift(node.data);
				if(node.parent) loop(node.parent);
			};
			loop(node);
			return fullPath;
		},
        // 树节点点击事件
		handleNodeClick(data, node){
			if(this.treeActiveId === data[this.treeProps.value]) return;
			this.treeActiveId = data[this.treeProps.value];
			this.$refs.Search.treeReset();
			const queryJson = [];
			if(this.columnData.treeDataSource === 'organize'){
				const nodePath = this.getNodePath(node);
				const currValue = nodePath.map((o) => o[this.treeProps.value]);
				queryJson.push({
					model:this.columnData.treeRelation,
					symbol:'EQ',
					value:currValue,
				});
				this.treeActiveId = currValue;
			}else{
				queryJson.push({
					model:this.columnData.treeRelation,
					symbol:'EQ',
					value:[data[this.treeProps.value]],
				});
			}
			this.search(queryJson);
		},
        // 处理删除操作
		handleDel(row){
			this.$confirm('确认删除吗', '提示', {
				type:'warning',
			})
				.then(() => {
					magic.core
						.service({
							url:'/api/form/instance',
							method:'delete',
							data:{
								templateId:this.modelId,
								id:row.id,
							},
						})
						.then(({data}) => {
							//TODO
							this.$message({
								type:'success',
								message:data.message,
								duration:1000,
								onClose:() => {
									this.initData();
								},
							});
						});
				});
		},
        // 新增，如果是类型编辑表格，则直接添加编辑行，否则弹出表单界面
		addHandle(){
			this.formVisible = true;
			this.$nextTick(() => {
				this.$refs.Form.init(
					this.formData,
					this.modelId,
					'',
					this.isPreview,
					this.columnData.useFormPermission,
					this.list,
					this.columnData.type,
				);
			});
		},
        // 更新指定行的数据
		updateHandle(row){
			this.formVisible = true;
			this.$nextTick(() => {
				this.$refs.Form.init(
					this.formData,
					this.modelId,
					row.id,
					this.isPreview,
					this.columnData.useFormPermission,
					this.list,
					this.columnData.type,
				);
			});
		},
        // 处理自定义事件，初始化指定的组件
		handleCustomEvent(item, row){
			this.row = row;
			this.widgetName = item.value;
			const initializeMethodName = 'initialize';
			this.$nextTick(() => {
				setTimeout(() => {
					const widget = this.$refs[this.widgetName];
					if(!widget || !widget.$el){
						this.$message.error(`组件 "${this.widgetName}" 未找到，请在项目中进行注册`);
						return;
					}
					if(typeof widget[initializeMethodName] !== 'function'){
						this.$message.error(`组件 "${this.widgetName}" 中未定义 "${initializeMethodName}" 初始化函数。`);
						return;
					}
					widget[initializeMethodName]();
				}, 100); // 确保延迟足够长以完成挂载
			});
		},
        //自定义操作按钮触发
		async fetchGeneralInterface(item, ids){
            // 触发 before-request 事件，并且传递一个 Promise 来控制是否继续
			try{
                // 是否监听了 `before-request` 事件
				if(this.$listeners['before-request']){
                    // 如果监听了，触发事件并等待 Promise
					await new Promise((resolve, reject) => {
						this.$emit('before-request', item, this.selection, {resolve, reject});
					});
				}
			}catch(error){
				console.log(error, '事件已被中止');
				return;
			}
            // 执行接口调用
			magic.core
				.service({
					url:`/api/form/instance/actions`,
					method:'put',
					data:{
						templateId:this.modelId,
						currentEventCode:item.value,
						ids:ids,
					},
				})
				.then(({data}) => {
					this.$message.success(data.message);
					this.initData();
                 // 调用成功，触发事件
					this.$emit('request-success', data);
				})
				.catch((error) => {
                 // 调用失败，触发事件
					this.$emit('request-error', error);
				})
				.finally(() => {
                 // 调用后事件
					this.$emit('after-request');
				});
		},
        // 根据按钮类型处理不同的操作
		handleDataBtn(item, row){
			if(item.type === '0'){
				this.headBtnsHandel(item, row);
			}else if(item.type === '1'){
				this.fetchGeneralInterface(item, [row.F_ID]);
			}
		},
        // 处理表头按钮的操作，包括新增、导入、导出和自定义事件
		headBtnsHandel(item, row){
            //自定义操作按钮
			if(item.type === '1'){
				this.fetchGeneralInterface(item, this.selectedIds);
				return;
			}
			const key = item.value;
            //新增
			if(key === 'add'){
				this.addHandle();
			}
            //导出
			if(key === 'download'){
				this.downloadVisible = true;
				this.$nextTick(() => {
					this.$refs.ExportBox.init(this.exportList);
				});
			}
            //导入
			if(key === 'upload'){
				this.uploadVisible = true;
				this.$nextTick(() => {
					this.$refs.UploadBox.init(this.modelId);
				});
			}
			if(!staticBtns.includes(item.value)){
				this.handleCustomEvent(item, row);
			}
		},
        // 处理选择变化，更新选中的项和全选/半选状态
		handleSelectionChange(selectedItems){
			selectedItems = selectedItems.map((item) => ({...item, checked:true}));
            // 获取选中的ID数组
			const selectedIds = selectedItems.map((item) => item.id);
			this.selectedIds = selectedIds;
			this.selection = selectedItems;
            // 更新列表项的 `checked` 状态
			this.list.forEach((item) => {
				item.checked = selectedIds.includes(item.id);
			});

            // 更新全选和半选状态
			if(this.componentMap[this.cardTemplateIdentity]){
				const selectedCount = selectedItems.length;
				const totalCount = this.list.length;

				this.indeterminate = selectedCount > 0 && selectedCount < totalCount;
				this.selectAllValue = selectedCount === totalCount;
			}
		},
        // 数据导出
		download(data){
			if(this.isPreview){
				return this.$message({message:'功能预览不支持数据导出', type:'warning'});
			}
			const query = {...this.listQuery, ...data};
            //TODO 接口待开发
			exportModel(this.modelId, query).then((res) => {
				if(!res.data.url) return;
				this.$commonUtils.downloadFile(res.data.url);
				this.$refs.ExportBox.visible = false;
				this.downloadVisible = false;
			});
		},
        // 根据列按钮类型处理编辑、查看详情或删除操作
		columnBtnsHandel(key, row, index){
			this.rowIndex = index;
			if(key === 'edit'){
				this.updateHandle(row);
			}
			if(key === 'detail'){
				this.goDetail(row);
			}
			if(key === 'remove'){
				this.handleDel(row);
			}
		},
        // 打开详情界面并初始化数据
		goDetail(row){
			this.detailVisible = true;
			this.$nextTick(() => {
				this.$refs.Detail.init(
					this.formData,
					this.modelId,
					row.id,
					this.columnData.useFormPermission,
				);
			});
		},
        // 刷新表单，重新加载数据（可选）
		refresh(){
			this.formVisible = false;
			this.initData();
		},
        // 重置查询条件为默认值，并重新触发搜索
		reset(){
            // 将查询条件恢复为默认状态
			this.listQuery.query.condition = [];

            // 使用缓存的条件（如果存在）来重新触发搜索
			this.search(this.cacheCondition.length ? [...this.cacheCondition] : [], true);
		},
        // 执行查询操作，并根据 `cache` 参数决定是否缓存查询条件
		search(queryJson = [], cache = false){
			if(cache){
                // 如果 `cache` 为 true，则更新缓存条件
				this.cacheCondition = [...queryJson];
			}else{
				this.listQuery.query.condition = queryJson;
			}

            // 更新查询条件，确保不会重复条件
			const uniqueConditions = [
				...(cache ? this.cacheCondition : this.listQuery.query.condition),
				...queryJson,
			].filter((item, index, self) =>
				index === self.findLastIndex((t) => t.model === item.model),
			);

            // 更新 `listQuery.query`，并将 `currentPage` 重置为 1
			this.listQuery.query = {
				matchLogic:'AND',
				condition:uniqueConditions,
			};
			this.listQuery.currentPage = 1;

            // 初始化数据
			this.initData();
		},
        // 打开高级查询界面
		openSuperQuery(){
			this.superQueryVisible = true;
			this.$nextTick(() => {
				this.$refs.SuperQuery.init();
			});
		},
        // 根据高级查询条件触发查询
		triggerSuperQuery(queryJson){
			this.listQuery.query = {
				matchLogic:queryJson.matchLogic,
				condition:queryJson.condition.map(({attr, ...item}) => ({
					...item,
					value:Array.isArray(item.value) ? item.value : [item.value],
				})),
			};
			this.listQuery.currentPage = 1;
			this.initData();
		},
        // 发送请求并返回数据，支持不同的 HTTP 方法
		request(url, method = 'get', data = {}){
			if(!url) return;
			return magic.core.service({
				url,
				method,
				data,
			});
		},
        // 设置表格加载函数，执行 afterOnload 钩子函数
		setTableLoadFunc(){
			const McTable = this.$refs.tableRef;
			const parameter = {
				data:this.list,
				attributes:McTable._props,
				events:McTable._events,
				methods:McTable,
				tableRef:McTable,
				request:this.request,
			};
			const func = getScriptFunc.call(
				this,
				this.columnData.funcs.afterOnload.func,
			);
			if(!func) return;
			func.call(this, parameter);
		},
        // 树节点过滤函数，判断节点是否符合过滤条件
		filterNode(value, data){
			if(!value) return true;
			return data[this.treeProps.label].indexOf(value) !== -1;
		},
        // 切换树的展开状态
		toggleTreeExpand(expands){
			this.keyword = '';
			this.refreshTree = false;
			this.expandsTree = expands;
			this.$nextTick(() => {
				this.refreshTree = true;
				this.$nextTick(() => {
					this.$refs.treeBox.setCurrentKey(null);
				});
			});
		},
        // 切换表格的展开状态
		toggleExpandList(){
			this.refreshTable = false;
			this.expandsTable = !this.expandsTable;
			this.$nextTick(() => {
				this.refreshTable = true;
			});
		},
        //懒加载树型数据(暂不支持)
		loadNode(node, resolve){
			const {treeInterfaceId, treeTemplateJson = []} = this.columnData;
			if(treeInterfaceId){
				const updatedTemplate = treeTemplateJson.map((element) => ({
					...element,
					defaultValue:node.data[element.relationField] || '',
				}));
				const query = {paramList:updatedTemplate};

				magic.core.service({
					url:`/api/system/DataInterface/${treeInterfaceId}/Actions/Preview`,
					method:'post',
					data:query,
				}).then(({data}) => {
					resolve(Array.isArray(data) ? data : []);
				});
			}
		},
        // 获取列的固定属性
		getFixed(item, i){
			if(i === 0 && this.columnData.groupField){
				if(this.columnList.some((o) => o.fixed === 'left')) return 'left';
				return false;
			}else if(this.columnData.childTableStyle !== 2){
				return item.fixed === 'none' ? false : item.fixed;
			}else{
				return false;
			}
		},
        // 切换行项，更新当前行索引并触发详情初始化
		changeItem(type){
			const newIndex = type === 'next' ? this.rowIndex - 1 : this.rowIndex + 1;
			if(newIndex < 0 || newIndex >= this.list.length) return;
			this.rowIndex = newIndex;
			this.$refs.Detail.init(
				this.formData,
				this.modelId,
				this.list[newIndex].id,
				this.columnData.useFormPermission,
			);
		},
        // 行双击事件，触发 'row-dblclick' 事件
		rowDblclick(row, column){
			this.$emit('row-dblclick', row, column);
			event.stopPropagation();
		},
        // 单元格点击事件，触发 'cell-click' 事件
		cellClick(row, column){
			this.$emit('cell-click', row, column);
			event.stopPropagation();
		},
        // 设置单元格样式
		cellStyle({column}){
			if(!this.cursomColumn.length) return;
			const findColumn = this.cursomColumn.find((item) => item.model === column.property);
			if(!findColumn?.columnStyle?.color) return;
			return {
				backgroundColor:generateLighterColor(findColumn.columnStyle.color),
			};
		},
        // 设置表头单元格样式
		headerCellStyle({column}){
			if(!this.cursomColumn.length){
				return {
					backgroundColor:'#F1F7FF',
				};
			}
			const findColumn = this.cursomColumn.find((item) => item.model === column.property);
			if(!findColumn?.columnStyle?.color) return;
			return {
				backgroundColor:findColumn?.columnStyle.color,
				fontWeight:'bold',
			};
		},
        // 扩展图标点击事件
		cellIconClick(item, type){
			this.$emit('cell-icon-click', item, type);
		},
        // 获取表头和扩展按钮国际化翻译
		getTrans(type, modelId, value){
			return t(`com.lexmis.magic.core.form.${type}.${modelId}.${value}`);
		},
		// 清空所选数据
		clearSelection(){
			this.$refs.tableRef.clearSelection();
			for(const item of this.list){
				item.checked = false;
			}
		},
		// 切换当前页
		handleCurrentChange(val){
			this.listQuery.currentPage = val;
			this.initData();
			this.$emit('current-change', val);
		},
		// 切换每页条数
		handleSizeChange(val){
			this.listQuery.pageSize = val;
			this.initData();
			this.$emit('size-change', val);
		},
		// 翻页模式下组件切换上下条时
		pageJump(direction){
			const newIndex = this.currentIndex + direction;

			// 不属于最后一张时递增索引
			if(newIndex >= 0 && newIndex < this.storedList.length){
				this.currentIndex = newIndex;
			}
			if(this.storedList.length === this.total){
				return;
			}
			// 如果是倒数第二张，模拟重新请求并更新数据
			if(newIndex >= this.storedList.length - 2){
				this.cachePageListQuery.currentPage += 1;
				this.changePageViewData();
			}
		},

	},
};
</script>
<style scoped lang="scss">
@import "../../style/global.scss";
.m-view-common-head {
	::v-deep .m-view-common-head__checkbox {
		margin-right: 10px;
	}
}

.table-footer{
	padding: 0 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	.bottom-left-before{
		display: flex;
		align-items: center;
	}
}
.extend-card{
	padding: 0 10px;
	height: calc(100vh - 175px);
	overflow-y: auto;
	display: flex;
	flex-wrap: wrap;
	.extend-item{
		margin-bottom: 24px;
	}
}
.data-empty{
	height: calc(100vh - 208px);
	display: flex;
	align-items: center;
	justify-content: center;
	margin:0 auto;
}
.column-scope{
	margin: 0 5px;
}
</style>